package com.mac.bluetoothbt.feature;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.PermissionChecker;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;

import com.clj.fastble.data.BleDevice;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.util.*;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static com.mac.bluetoothbt.feature.Actions.ACTION_STARTSCAN;

/**
 * 蓝牙连接界面
 *
 * @author wyh
 */
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
    BroadcastReceiver mainActivityReceiver;
    boolean linkState = false;
    boolean linking = false;
    private ArrayList<Map<String, Object>> scaneddevicedata = new ArrayList<Map<String, Object>>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView imageView = findViewById(R.id.scanleImage);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (linking || linkState) {
                    Toast.makeText(getApplicationContext(), "蓝牙链接中", Toast.LENGTH_SHORT).show();
                    return;
                }
                scanBarcode(v);
            }
        });
//打开时申请权限
        requestCorseLocation();
//注册接收器
        mainActivityReceiver = new MainActivityReceiver(new Handler(), this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Actions.ACTION_REQUEST_LOCATION_PERMISSION);
        intentFilter.addAction(Actions.ACTION_BLE_CONNECTED);
        intentFilter.addAction(Actions.ACTION_TIMEOUT);
        intentFilter.addAction(Actions.ACTION_TIMEOUT);
        intentFilter.addAction(Actions.ACTION_CONNECT_BY_MAC_SUCCESS);
        intentFilter.addAction(Actions.ACTION_CHAR_RETURN);
        intentFilter.addAction(Actions.ACTION_SCANNING);
        intentFilter.addAction(Actions.ACTION_SCANEND);
        registerReceiver(mainActivityReceiver, intentFilter);
//开启Service
        //startBluetoothService(); //原生api

        //使用FastBle
        startFastBleService();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mainActivityReceiver);
    }

    public void scanBarcode(View view) {
        IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);
        integrator.setPrompt("请对准二维码进行扫描"); //底部的提示文字，设为""可以置空
        integrator.setCameraId(0); //前置或者后置摄像头
        integrator.initiateScan();// 初始化扫描
    }

    public void onLogin_Button_Clicked(View view) {
        EditText macinEdittext = findViewById(R.id.EditTextMacIn);
        String mac = macinEdittext.getText().toString().toUpperCase();
        if (checkMac(mac)) {
            sendBroadcast(new Intent(Actions.ACTION_LINKBT_MAC).putExtra("mac_input", mac));
        }
    }

    private class Timeout extends Thread {
        @Override
        public void run() {
            try {
                Thread.sleep(20000);
                sendBroadcast(new Intent(Actions.ACTION_TIMEOUT));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (intentResult != null) {
            if (intentResult.getContents() == null) {
                if (resultCode == -1) {
                    Toast.makeText(this, "无法获取内容", Toast.LENGTH_SHORT).show();
                }

            } else {
                //获取内容，连接蓝牙
                String strQr = intentResult.getContents();
                StringBuilder stringBuilder = new StringBuilder(strQr);
                stringBuilder.insert(2, ":").insert(5, ":").insert(8, ":").insert(11, ":").insert(14, ":");
                strQr = stringBuilder.toString();
                if (checkMac(strQr.split(" ")[0])) {
                    sendBroadcast(new Intent(Actions.ACTION_LINKBT_MAC).
                            putExtra("mac_input", strQr.split(" ")[0]));
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    sendBroadcast(new Intent(Actions.ACTION_REQUEST_LOCATION_PERMISSION_SUCCESS));
                }
                break;
            default:
                break;
        }
    }

    /**
     * 开启蓝牙service
     */
    private void startFastBleService() {
        Intent intent = new Intent(MainActivity.this, FastBleService.class);
        startService(intent);
    }

    private void requestCorseLocation() {
        if (PermissionChecker.checkSelfPermission(this, ACCESS_COARSE_LOCATION) !=
                PermissionChecker.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{ACCESS_COARSE_LOCATION},
                    1);
        }
    }

    private boolean checkMac(String mac) {
        if (!BluetoothAdapter.checkBluetoothAddress(mac)) {
            Toast.makeText(getApplicationContext(), "mac格式错误", Toast.LENGTH_LONG).show();
            sendBroadcast(new Intent(ACTION_STARTSCAN));
            return false;
        } else {
            return true;
        }
    }

    private int connectedBleDeviceCount = 0;

    private void newDeviceFound(BleDevice device, boolean added) {
        for (Map<String, Object> dev :
                scaneddevicedata) {
            String mac = (String)dev.get("mac");
            if (mac != null && mac.equals(device.getMac())) {
                return;
            }
        }
        ListView deviceList = findViewById(R.id.Devices_Listview);
        Map<String, Object> map = new HashMap<String, Object>(16);
        map.put("name", device.getName());
        map.put("mac", device.getMac());
        map.put("added", added);
        if (added) {
            scaneddevicedata.add(connectedBleDeviceCount, map);
            connectedBleDeviceCount++;
        } else {
            scaneddevicedata.add(map);
        }
        deviceList.setAdapter(new BleAdapter(MainActivity.this, scaneddevicedata,
                R.layout.ble_list_item
                , new String[]{"name", "mac", "added"}
                , new int[]{R.id.up_text, R.id.down_text, R.id.img_his}
        ));
        deviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                sendBroadcast(new Intent(Actions.ACTION_LINKBT_MAC).putExtra("mac_input", (String) scaneddevicedata.get(position).get("mac")));
            }
        });
    }

    private void showAllDevices(List<BleDevice> devices) {
        for (BleDevice bleDevice : devices) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("name", bleDevice.getName());
            map.put("mac", bleDevice.getMac());
            scaneddevicedata.add(map);
        }
        removeDuplicate(scaneddevicedata);

        ListView deviceList = findViewById(R.id.Devices_Listview);
        deviceList.setAdapter(new BleAdapter(MainActivity.this, scaneddevicedata,
                R.layout.ble_list_item
                , new String[]{"name", "mac", "added"}
                , new int[]{R.id.up_text, R.id.down_text, R.id.img_his}
        ));
        deviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                sendBroadcast(new Intent(Actions.ACTION_LINKBT_MAC).putExtra("mac_input", (String) scaneddevicedata.get(position).get("mac")));
            }
        });
    }

    public static List removeDuplicate(List list) {
        HashSet h = new HashSet(list);
        list.clear();
        list.addAll(h);
        return list;
    }


    private class MainActivityReceiver extends BroadcastReceiver {
        private final Handler handler;
        private final Context localcontext;

        public MainActivityReceiver(Handler handler, Context context) {
            this.handler = handler;
            this.localcontext = context;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() == null) {
                return;
            }
            switch (intent.getAction()) {
                case Actions.ACTION_REQUEST_LOCATION_PERMISSION:
                    requestCorseLocation();
                    break;
                case Actions.ACTION_BLE_CONNECTED:
                    Log.d("DEBUG", "ACTION_BLE_CONNECTED");
                    startActivity(new Intent().setClass(MainActivity.this, Main2Activity.class));
                    linkState = true;
                    break;
                case Actions.ACTION_TIMEOUT:
                    linking = false;
                    if (!linkState) {
                        Toast.
                                makeText(getApplicationContext(), "蓝牙连接超时", Toast.LENGTH_LONG).show();
                    }
                    break;
                case Actions.ACTION_CONNECT_BY_MAC_SUCCESS:
                    final String[] services = intent.getStringArrayExtra("services");

                    setContentView(R.layout.service);
                    ListView listView = (ListView) findViewById(R.id.serviceList);
                    listView.setAdapter(new ArrayAdapter<String>(localcontext,
                            android.R.layout.simple_list_item_1, services));
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            sendBroadcast(new Intent(Actions.ACTION_SERVICE_SELECTED)
                                    .putExtra("uuid", services[position]));
                        }
                    });
                    break;
                case Actions.ACTION_CHAR_RETURN:
                    final String[] charuuids = intent.getStringArrayExtra("uuid");
                    listView = (ListView) findViewById(R.id.serviceList);
                    listView.setAdapter(new ArrayAdapter<String>(localcontext,
                            android.R.layout.simple_list_item_1, charuuids));
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            sendBroadcast(new Intent(Actions.ACTION_CHAR_SELECTED)
                                    .putExtra("uuid", charuuids[position]));
                        }
                    });
                    break;
                case Actions.ACTION_SCANNING:
                    BleDevice newdevice = intent.getParcelableExtra("newdevice");
                    boolean added = intent.getBooleanExtra("added", false);
                    newDeviceFound(newdevice, added);
                    break;
                case Actions.ACTION_SCANEND:
//                    ParcelableBleDevice scanResultList = intent.getParcelableExtra("devices");
//                    List<BleDevice> bleDeviceList = scanResultList.getBledeviceList();
//                    showAllDevices(bleDeviceList);
                    break;
                default:
                    break;
            }
        }
    }
}
